import {useState} from 'react';
import { Button, Checkbox, Form,Input,Spin ,message} from 'antd';
import {history} from "umi"
import useStorage from "@/hooks/userStorage";
import "./index.css"
import * as api from "@/api/users"

const Login= () => {
  // 使用自定义的本地存储
  let [,tokenMethod] = useStorage('qf-token')
  let [,userMethod] = useStorage('user-info')
  let [,permissionMethod] = useStorage('btn-permission')
  // 加载动画
  let [loading,setLoading] = useState<boolean>(false)

  // 表单验证通过,调用onFinish
  const onFinish = async (values: any) => {
    console.log('Success:', values);
    // 打开加载动画
    setLoading(true)
    try{
      // 发起登录请求
      let res = await api.loginApi(values.username,values.password)
      // console.log(res)
      // 关闭加载动画
      setLoading(false)
      // 如果登陆成功
      if(res.data.state){
        //1.存token
        tokenMethod.set(res.data.token)
        //2.存用户信息
        userMethod.set(res.data.userInfo)
        //3.存按钮权限
        permissionMethod.set(res.data.permission)
        //4.跳转到主页
        history.push('/home')
        //5.成功提示框
        message.open({
          type:'success',
          content:res.data.msg
        })    
      }
    }catch(e){
      console.log(e)
      // 失败提示框
      message.open({
        type:'error',
        content:'登陆失败'
      })
    }
  };
  // 表单验证不通过
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  // 规则校验
  // 用户名校验
  const validatUsername = (rules:any,value:string) => {
    // 如果通过 返回Promise.resolve  如果不通过 返回Promise.reject
    if(!value){
      return Promise.reject('用户名不能为空')
    }
    if(value.length < 3){
      return Promise.reject('用户名的长度不能小于3位')
    }else{
      return Promise.resolve('')
    }  
  }
  // 密码校验
  const validatPassword = (rules:any,value:string) => {
    let reg = /^[\-_\w\d]{3,10}$/
    if(!value){
      return Promise.reject('密码不能为空')
    }
    if(reg.test(value)){
      return Promise.resolve()
    }else{
      return Promise.reject('密码为3-10位')
    }
  }
  return (
    <Spin tip='正在登入...' spinning={loading} className='login-spin' >
      <div className="login-page">
        {/* 全屏背景 */}
        <div className="bg">
        </div>
        {/* 登录框样式 */}
        <div className="login-container">
          <h1 className='title'>银行管理系统</h1>
          <Form
            name="loginForm"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 12 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off">
            <Form.Item label="用户名" name="username" rules={[{ required: true, validator: validatUsername }]}>
              <Input />
            </Form.Item>
            <Form.Item label="密码" name="password" rules={[{ required: true, validator: validatPassword}]}>
              <Input.Password />
            </Form.Item>
            <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 8, span: 16 }}>
              <Checkbox>七天免登录</Checkbox>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit"> 点击登录</Button>
            </Form.Item>
        </Form>
        </div>   
      </div>
    </Spin>
  );
};
export default Login